<?php

namespace App\Services;


use App\Constants\RedisKeyConstants;
use App\Events\AtLogEvent;
use App\Models\CronModel;
use App\Models\DrawLogModel;
use App\Models\EggsModel;
use App\Models\FoodUseLogModel;
use App\Models\GoodsInfo;
use App\Models\GoodsUseLogModel;
use App\Models\PrizeModel;
use App\Models\TaskModel;
use App\Models\UserKnapsack;
use App\Models\UserLandModel;
use App\Models\UserModel;
use App\Models\UserSignInModel;
use Carbon\Carbon;
use Framework\BaseService;
use Framework\Hope;
use Framework\ModelEncryptionTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Hash;
use Framework\Jwt;

class UserService extends BaseService
{
    use ModelEncryptionTrait;
    private $jwt;

    public function __construct(Jwt $jwt)
    {
        $this->jwt = $jwt;
    }


    /** 用户注册
     * @param String $phone
     * @param string $code
     * @param string $password
     * @param string $confirm_password
     * @param string $invite_code
     * @param string $device
     * @param string $uuid
     * @param string $ip
     * @return array
     * @throws \Throwable
     */
    public function register( $phone,  $code,  $password)
    {
        if (!$this->validatePhone($phone)) {
            $this->retError('请输入正确的手机号');
        }
        if(!preg_match("/^[a-z\d]{6,12}$/i",$password)){
            $this->retError('密码格式不正确');
        }

        app(SmsService::class)->checkSmsCode($phone, $code);
        $flg = UserModel::query()->where('phone', $phone)->exists();
        if ($flg) {
            $this->retError('手机号已存在');
        }
        $info = new UserModel();
        $info->nickname = '想见'.rand(1,999999);
        $info->avatar = '';
        $info->phone = $phone;
        $info->password = Hash::make($password);
        $info->saveOrFail();
        $jwt_str = $this->jwt->getToken((string)$info->id);

        $arr = array(
            'jwt' => $jwt_str, 'userInfo' => $info
        );

        return $arr;
    }


    public function getUserInfo($user_id)
    {
        return UserModel::findOrFail($user_id);
    }


    public function getTaskList($user_id)
    {
        return TaskModel::all();
    }

    /**
     * 忘记登录密码
     * @param string $password
     * @param string $code
     * @param string $password_confirmation
     * @return array
     * @throws \Throwable
     */
    public function forgetLoginPassword( $phone, $code, $password)
    {
        $info = UserModel::query()->wherePhone($phone)->first();
        if (!$info) {
            $this->retError('未找到账户信息');
        }
        //验证短信验证码
        app(SmsService::class)->checkSmsCode($phone, $code);

        $info->password = Hash::make($password);
        $info->saveOrFail();

        return true;
    }




    /**
     * @param string $password
     * @param string $code
     * @param string $password_confirmation
     * @return array
     * @throws \Throwable
     */
    public function forgetPayPassword(int $user_id, string $code, string $password, string $password_confirmation)
    {
        if ($password !== $password_confirmation) {
            $this->retError('两次输入的密码不一致');
        }

        //获取手机号,进行短信验证
        $info = UserModel::findOrFail($user_id);

        if (!$info) {
            $this->retError('手机号查找失败');
        }

        //验证短信验证码
        app(SmsService::class)->checkSmsCode($info->phone, $code);

        //保存支付密码
        $info->pay_password = Hash::make($password);
        $info->saveOrFail();

        return true;
    }


    /**
     * @param string $password
     * @param string $code
     * @param string $password_confirmation
     * @return array
     * @throws \Throwable
     */
    public function setPayPassword(int $user_id, string $password, string $password_confirmation)
    {
        if ($password !== $password_confirmation) {
            $this->retError('两次输入的密码不一致');
        }

        //保存支付密码
        $info = UserModel::findOrFail($user_id);
        $info->pay_password = Hash::make($password);
        $info->saveOrFail();
        return true;
    }

    /**
     * @param string $password
     * @param string $code
     * @param string $password_confirmation
     * @return array
     * @throws \Throwable
     */
    public function editPayPassword(int $user_id, string $password, string $password_confirmation, string $old_password)
    {
        if ($password !== $password_confirmation) {
            $this->retError('两次输入的密码不一致');
        }

        $info = UserModel::findOrFail($user_id);
        if (!Hash::check($old_password, $info->pay_password)) {
            $this->retError('原密码不正确');
        }

        if (Hash::check($password, $info->pay_password)) {
            $this->retError('新密码不能与原密码一样');
        }

        //保存支付密码
        $info->pay_password = Hash::make($password);
        $info->saveOrFail();

        return true;
    }

    /**
     * @param string $phone
     * @param string $password
     * @return array
     */
    public function Login(string $phone, string $password)
    {
        if (!$this->validatePhone($phone)) {
            $this->retError('请输入正确的手机号');
        }
        $user = UserModel::query()
            ->where('phone', $phone)
            ->first();

        if (empty($user)) {
            $this->retError('手机号不存在');
        }

        if (!Hash::check($password, $user['password'])) {
            $this->retError('密码不正确');
        }

        $jwt_str = $this->jwt->getToken((string)$user['id']);
        $login_data['jwt'] = $jwt_str;
        $login_data['userInfo'] = $user;

        return $login_data;
    }

    public function codeLogin($phone, $code)
    {
        if (!$this->validatePhone($phone)) {
            $this->retError('请输入正确的手机号');
        }
        $user = UserModel::query()
            ->where('phone', $phone)
            ->first();

        if (empty($user)) {
            $this->retError('手机号不存在');
        }
        app(SmsService::class)->checkSmsCode($phone, $code);
        $jwt_str = $this->jwt->getToken((string)$user['id']);
        $login_data['jwt'] = $jwt_str;
        $login_data['userInfo'] = $user;

        return $login_data;
    }





    /**
     * @param string $user_id
     * @param string $old_pwd
     * @param string $new_pwd
     * @throws \Throwable
     */
    public function edit_password(string $user_id, string $old_pwd, string $new_pwd, string $password_confirm)
    {
        if ($new_pwd != $password_confirm) {
            $this->retError('新密码和确认密码不一样');
        }
        $info = UserModel::findOrFail($user_id);
        if (!Hash::check($old_pwd, $info->password)) {
            $this->retError('原密码不正确');
        }
        $info->password = Hash::make($new_pwd);
        $info->saveOrFail();
        return true;
    }

    /**
     * @param $value
     * @return bool
     */
    public function validatePhone($value)
    {
        $rule = '/^13\d{9}$|^14\d{9}$|^15\d{9}$|^16\d{9}$|^17\d{9}$|^18\d{9}|^19\d{9}$/';

        if (empty($value) || !preg_match($rule, $value)) {
            return false;
        }
        return true;
    }



    /**
     * @param $code
     * @param $phone
     * @return false
     */
    public function verifyCode($code, $phone)
    {
        $redis = Hope::getRedis();
        $sms = $redis->get('sms:' . $phone);
        if ($code != $sms) {
            return false;
        }

    }


    /** 修改用户昵称和头像
     * @param int $user_id
     * @param string $nickname
     * @param string $avatar
     * @return bool
     */
    public function editNickname(int $user_id, string $nickname): bool
    {
        if(!$nickname){
            $this->retError("昵称不能为空");
        }
        return UserModel::query()
            ->where('id', $user_id)
            ->update([
                'nickname' => $nickname,
            ]);
    }










}
